// 云函数入口文件
const cloud = require('wx-server-sdk')
const request = require('request')

cloud.init()
const db = cloud.database();
const _ = db.command

function getNewToken() {
  //接口地址：https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  //返回数据格式: {"access_token": "ACCESS_TOKEN", "expires_in": 7200}

  let appid = 'wx159a31cbaf45bec5'; //公众号appid
  // let appsecret = '5280cac89916b7810922e63dc70278ac'
  // wx159a31cbaf45bec5
  // 3234b39bb6efbddb496b62ba7617ac02
  //let appsecret = '9df6112301cf084fe7d16327f3ea5131'; //小程序的 app secret (在微信小程序管理后台获取)
  let appsecret = '3234b39bb6efbddb496b62ba7617ac02';
  let grant_type = "client_credential"; //授权（必填）
  let url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
        url: url,
        method: "GET",
      },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            let newToken = JSON.parse(body)
            return resolve(newToken)
          } else {
            return reject(err)
          }
        })
    } catch (e) {
      return reject(err)
    }
  })

}

function http_request() {
  let url = "http://test.jian24.com/merchant/unread-msg-count/" 
  //新建promise对象，发起http统一下单请求
  return new Promise((resolve, reject) => {
    try {
      request.post({
        url: url,
        method: "GET",
      },
        function (error, response, body) {
          if (!error && response.statusCode == 200) {
            let res = JSON.parse(body)
            return resolve(res)
          } else {
            return reject(err)
          }
        })
    } catch (e) {
      return reject(err)
    }
  })

}

// 云函数入口函数
exports.main = async (event, context) => {
  let httpToken = await getNewToken();

  return httpToken
  // let ticket = {
  //   current_user_exchange_count:0,
  //   exchange_count_per_user:1,
  //   id:0,
  //   image:'/images/coins.png',
  //   name:'5积分券（全场通用）',
  //   need_likes:50,
  //   open:true,
  //   total_count:20,
  //   value:0
  // }
  // let insert = await db.collection('activity_settings').doc('5cf7770f47882f40e4a3ceaa').update({
  //   data: {
  //     tickets: _.push(ticket)
  //   }
  // })
}